import { FC, useEffect, useState } from "react";
import {  Pagination, PaginationProps } from "antd";
import { DEFAULT_PAGESIZE, PAGENAME, PAGESIZNAME } from "../../concats";
import { useNavigate, useLocation, useSearchParams } from "react-router-dom";
type propsType = {
  total: number;
};

const TablePageConfig: FC<propsType> = (props) => {
  const { total } = props;
  const [current, setcurrent] = useState(1);
  const [pagesize, setpagesize] = useState(DEFAULT_PAGESIZE);
  const nav = useNavigate();
  const { pathname } = useLocation();
  const [params] = useSearchParams();
  useEffect(() => {
    const pageSize = params.get(PAGESIZNAME);
    const page = params.get(PAGENAME);
    setcurrent(parseInt(page || "") || 1);
    setpagesize(parseInt(pageSize || "") || DEFAULT_PAGESIZE);
  }, [params]);

  const onChange: PaginationProps["onChange"] = (pages, pageSize) => {
    params.set(PAGENAME, pages.toString());
    params.set(PAGESIZNAME, pageSize.toString());
    nav({
      pathname,
      search: params.toString(),
    });
  };

  return (
    <Pagination
      current={current}
      total={total}
      pageSize={pagesize}
      showSizeChanger
      onChange={onChange}
    />
  );
};

export default TablePageConfig;
